# Maintainer: Sebastian Ehlert <awvwgk@disroot.org>

_realname=fpm
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.12.0
_bootstrap_ver=0.8.2
pkgrel=2
pkgdesc="Fortran package manager (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64') # 'clang64' 'clangarm64')
url="https://github.com/fortran-lang/fpm"
msys2_references=(
  'aur: fortran-fpm'
)
license=('spdx:MIT')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-omp"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran"))
makedepends=("${MINGW_PACKAGE_PREFIX}-fc"
             "git")
optdepends=("git: Support for fetching projects with git")
source=("${url}/releases/download/v${pkgver}/fpm-${pkgver}.zip"
        "${url}/releases/download/v${_bootstrap_ver}/fpm-${_bootstrap_ver}.F90"
        "fpm_0_12_0_gcc15_bugfix.patch")
sha256sums=('b519b614c693dc26f553f0eb902fc707adab9d1759f17ff098412c14d6b290fe'
            '0c95309f365a40900108f3325e17e99a0456ce76046c37326349bf61b3df447a'
            '3b3263865a4b2c4d91ee34229adfa09fd1151af4c25fad2394d7b61ae564c10e')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"

  apply_patch_with_msg fpm_0_12_0_gcc15_bugfix.patch
}

build() {
  cd "${srcdir}/${_realname}-${pkgver}"
  local _build="build-${MSYSTEM}"
  if [[ ${MINGW_PACKAGE_PREFIX} != *-clang-* ]]; then
    _fc="${MINGW_PREFIX}/bin/gfortran"
    _fflags="-g -O3 -fbacktrace -fopenmp"
  else
    _fc="${MINGW_PREFIX}/bin/flang"
    _fflags="-g -O3 -fopenmp"
  fi

  mkdir -p "${_build}/bootstrap"
  "${_fc}" -J "${_build}/bootstrap" -o "${_build}/bootstrap/fpm" "${srcdir}"/fpm-${_bootstrap_ver}.F90

  "${_build}/bootstrap/fpm" install \
    --compiler "${_fc}" \
    --flag "${_fflags}" \
    --prefix "${_build}"
}

package() {
  cd "${srcdir}/${_realname}-${pkgver}"

  install -Dm755 build-${MSYSTEM}/bin/fpm "${pkgdir}"${MINGW_PREFIX}/bin/fpm

  install -Dm644 LICENSE "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
